import { CheckItem } from '../../types/checkItem'
import { execute, select } from '../../utils/db'
import { Page, PageReq } from '../../types/page'

export class CheckItemDao {
  /**
   * 创建检查项目
   */
  static async create(checkItem: Omit<CheckItem, 'id'>): Promise<number | undefined> {
    const result = await execute(
      'INSERT INTO check_item (name) VALUES (?) RETURNING id',
      [checkItem.name]
    )
    return result?.lastInsertId
  }

  /**
   * 更新检查项目
   */
  static async update(id: number, checkItem: Partial<CheckItem>): Promise<void> {
    if (checkItem.name) {
      await execute(
        'UPDATE check_item SET name = ? WHERE id = ?',
        [checkItem.name, id]
      )
    }
  }

  /**
   * 删除检查项目
   */
  static async delete(id: number): Promise<void> {
    await execute('DELETE FROM check_item WHERE id = ?', [id])
  }

  /**
   * 获取检查项目详情
   */
  static async getById(id: number): Promise<CheckItem> {
    const result = await select<CheckItem>(
      'SELECT * FROM check_item WHERE id = ? LIMIT 1',
      [id]
    )
    return result[0]
  }

  /**
   * 获取检查项目列表
   */
  static async list(): Promise<CheckItem[]> {
    const result = await select<CheckItem[]>('SELECT * FROM check_item')
    return result
  }

  /**
   * 分页查询检查项目列表
   */
  static async page(params: PageReq<CheckItem>): Promise<Page<CheckItem>> {
    const { pageNum, pageSize } = params
    const offset = (pageNum - 1) * pageSize
    const checkItem = params.params
    
    const condition = checkItem.name ? 'WHERE name LIKE ?' : ''
    const values = checkItem.name ? [`%${checkItem.name}%`] : []

    const [totalResult, listResult] = await Promise.all([
      select('SELECT COUNT(*) as count FROM check_item ' + condition, values),
      select(`SELECT * FROM check_item ${condition} LIMIT ${pageSize} OFFSET ${offset}`, values)
    ])

    return {
      total: totalResult[0].count || 0,
      list: (listResult as unknown as CheckItem[]) || []
    }
  }
}